import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'
import { validatenull } from '@/libs/validate.js'

// 路由数据
import { frameInRoutes } from '@/router/routes'
import routes from './routes'

import ApiNode from '@/api/system.node'

import ApiMember from '@/api/system.member'

import layoutHeaderAside from '@/layout/header-aside'
const _import = require('@/libs/util.import.' + process.env.NODE_ENV)

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter);

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes
});


// let routerFlag = false;

let buttonAccess = [];

function checkToken () {
  // return true;
  return !validatenull(util.cookies.get('token'))
}

function parseTreeToMenu (list) {

  var menu = [];

  for (var i = 0; i < list.length; i ++) {
    var node = list[i];

    if (node.status != 1) continue;
    if (node.showStatus != 1) continue;

    var item = {
      path : node.component,
      title: node.title,
      icon : node.style,
    };

    if (node.children) {
      item.children = parseTreeToMenu(node.children);
      if (item.children.length == 0) delete item.children;
    }

    menu.push(item);
  }

  return menu;
  // console.log(tree);
}

function parseRouter (list, routerList = []) {

  for (var i = 0; i < list.length; i ++) {
    var node = list[i];

    if (node.showStatus == 0) buttonAccess.push(node.shortName);

    if (node.status != 1) continue;

    if (node.children) {
      parseRouter(node.children, routerList);
    }

    if (! node.component) continue;
    if (node.component.split('/').length < 3) continue;

    try {
      // cache = true, 页面缓存，name 值跟页面定义的name相等才会正确的缓存
      var item = {
        path: node.component,
        name: node.component.substring(1).replace('/', '-'),
        component: _import(node.component.substring(1)),
        meta: { auth: true, title: node.title, cache: true,},
      };
      // console.log(item)
      routerList.push(item);
    } catch (err) {
      console.error(err);
    }
  }

  return routerList;
}

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {

  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('d2admin/page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('d2admin/size/isLoaded')

  // 进度条
  NProgress.start();

  if (checkToken()) {
    // 已经登录

    // 检查动态路由是否已经加载
    // routerFlag = true;
    if (! window.routerFlag) {
      // 先初始化，防止重新登录其他角色用户是会没有加载到新的权限
      buttonAccess = [];
      // 获取菜单树
      store.commit('d2admin/menu/asideSet', []);
      var tree = await ApiMember.getMenuList();
      // var tree = await ApiNode.getNodeTree();

      // 增加路由
      var routerList = parseRouter(tree);
      // var routerList = parseRouter(tree.list);
      store.commit('d2admin/menu/buttonAccessSet', buttonAccess);
      
      var myRoutes = [
        {
          path: '/',
          component: layoutHeaderAside,
          children: routerList,
        }
      ];

      router.addRoutes(myRoutes);

      // 多标签页
      store.commit('d2admin/page/init', [].concat(frameInRoutes, myRoutes))

      // 左侧菜单栏
      var menu = parseTreeToMenu(tree);
      // console.log(menu);
      // var menu = parseTreeToMenu(tree.list);
      store.commit('d2admin/menu/asideSet', menu);

      // 全局加载路由状态设置为true，登出时设置为false
      window.routerFlag = true;

      next({path: to.path});

    }
    else {
      next();
    }

  } else {
    // 未经登录
    console.log('login')

    // 验证当前路由所有的匹配中是否需要有登陆验证的
    if (to.matched.some(r => r.meta.auth)) {
      if (checkToken()) {
        // token不为空,直接放行
        next();
      } else {
        // 没有token 跳转到登陆界面
        next({
          name: 'login'
        });
      }
    } else {
      next();
    }
   
    // next({path: '/login'});
  }

  return;


  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (to.matched.some(r => r.meta.auth)) {

    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    const token = util.cookies.get('token')

    store.commit('d2admin/menu/asideSet', res.role)

    //

    if (token && token !== 'undefined') {
      next()
    } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
      // https://github.com/d2-projects/d2-admin/issues/138
      NProgress.done()
    }

  } else {
    // 不需要身份校验 直接通过
    next()
  }
})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('d2admin/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
